package com.nullpointer.playerinfo.bungee;

import java.sql.SQLException;
import java.util.UUID;

import com.nullpointer.playerinfo.common.Base;
import com.nullpointer.playerinfo.common.objects.Player;

import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;

public class Listeners implements Listener {

    @EventHandler
    public void onPlayerDisconnect(PlayerDisconnectEvent event) {
        UUID playerUUID = event.getPlayer().getUniqueId();
        Player player = Base.playerMap.get(playerUUID);
        // 移除缓存
        Base.playerMap.remove(playerUUID);
        // 取消计时器
        PlayerInfoBungee.playerTimerMap.get(playerUUID).cancel();
        PlayerInfoBungee.runTaskAsynchronously(() -> {
            try {
                PlayerInfoBungee.mysql.savePlayer(player); // 保存数据
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });
    }

    @EventHandler
    public void onPlayerConnect(PostLoginEvent event) {
        ProxiedPlayer proxiedPlayer = event.getPlayer();
        UUID playerUUID = proxiedPlayer.getUniqueId();
        PlayerInfoBungee.runTaskAsynchronously(() -> {
            Player player;
            try {
                if (PlayerInfoBungee.mysql.havePlayer(playerUUID)) {
                    player = PlayerInfoBungee.mysql.getPlayer(playerUUID);
                } else {
                    player = new Player(proxiedPlayer.getName(), proxiedPlayer.getUniqueId());
                    PlayerInfoBungee.mysql.savePlayer(player);
                }
                Base.playerMap.put(playerUUID, player);

                // 计时器TODO:bug
                PlayerInfoBungee.playerTimerMap.put(
                    playerUUID, 
                    PlayerInfoBungee.runTaskTimerAsynchronously(new Runnable() {
                        int second = 0;
                        int totalSecond = player.getTotalOnlineTime();
                        @Override
                        public void run() {
                            second++;
                            totalSecond++;
                            player.setOnlineTime(second);
                            player.setTotalOnlineTime(totalSecond);
                        }
                        
                    }, 1));
            } catch (IllegalArgumentException | IllegalStateException | SQLException e) {
                e.printStackTrace();
            }
        });

    }
}
